{% extends "base.html" %}
{% block title %}开通会员 - 短视频去水印{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="page-title">
                <h3>开通会员</h3>
            </div>
        </div>
    </div>
    <div class="row">
        <!-- 会员套餐 -->
        <div class="col-12 col-sm-6 col-md-4">
            <ul class="pricing">
                <li>
                    <h1><img src="/static/images/vip/qtvip.png" style="height:25px;width:25px">金牌月卡 <img
                            src="/static/images/vip/tuijian.png" style="height:25px;width:25px"></h1>
                </li>
                <li>金牌月卡独特标识</li>
                <li>有效期：自开通起 <span style="color:red">{{ vip_plans['month'].days }}</span> 天</li>
                <li>每日解析次数：<span style="color:red">{{ vip_plans['month'].daily_limit }}</span> 次</li>
                <li>接口权限：有</li>
                <li>
                    <h3 style="margin-top:0;">￥{{ vip_plans['month'].price }}</h3>
                    <span>原价：￥30</span>
                </li>
                <li>
                    <select id="paytype_1" class="form-control custom-select">
                        <option value="">请选择</option>
                        <option value="alipay">支付宝</option>
                        <option value="wxpay">微信</option>
                    </select>
                </li>
                <li>
                    <button type="button"
                            onclick="createOrder('1', document.getElementById('paytype_1').value)"
                            class="btn btn-primary btn-rounded">
                        立即开通
                    </button>
                </li>
            </ul>
        </div>
        <div class="col-12 col-sm-6 col-md-4">
            <ul class="pricing">
                <li>
                    <h1><img src="/static/images/vip/byvip.png" style="height:25px;width:25px">钻石半年卡 <img
                            src="/static/images/vip/tuijian.png" style="height:25px;width:25px"></h1>
                </li>
                <li>钻石半年卡独特标识</li>
                <li>有效期：自开通起 <span style="color:red">{{ vip_plans['season'].days }}</span> 天</li>
                <li>每日解析次数：<span style="color:red">{{ vip_plans['season'].daily_limit }}</span> 次</li>
                <li>接口权限：有</li>
                <li>
                    <h3 style="margin-top:0;">￥{{ vip_plans['season'].price }}</h3>
                    <span>原价：￥180</span>
                </li>
                <li>
                    <select id="paytype_2" class="form-control custom-select">
                        <option value="">请选择</option>
                        <option value="alipay">支付宝</option>
                        <option value="wxpay">微信</option>
                    </select>
                </li>
                <li>
                    <button type="button"
                            onclick="createOrder('2', document.getElementById('paytype_2').value)"
                            class="btn btn-primary btn-rounded">
                        立即开通
                    </button>
                </li>
            </ul>
        </div>
        <div class="col-12 col-sm-6 col-md-4">
            <ul class="pricing">
                <li>
                    <h1><img src="/static/images/vip/hjvip.png" style="height:25px;width:25px">至尊年卡 <img
                            src="/static/images/vip/tuijian.png" style="height:25px;width:25px"></h1>
                </li>
                <li>至尊年卡独特标识</li>
                <li>有效期：自开通起 <span style="color:red">{{ vip_plans['year'].days }}</span> 天</li>
                <li>每日解析次数：<span style="color:red">{{ vip_plans['year'].daily_limit }}</span> 次</li>
                <li>接口权限：有</li>
                <li>
                    <h3 style="margin-top:0;">￥{{ vip_plans['year'].price }}</h3>
                    <span>原价：￥360</span>
                </li>
                <li>
                    <select id="paytype_3" class="form-control custom-select">
                        <option value="">请选择</option>
                        <option value="alipay">支付宝</option>
                        <option value="wxpay">微信</option>
                    </select>
                </li>
                <li>
                    <!--<button type="button" onclick="ktvip('3')" class="btn btn-primary btn-rounded">立即开通</button>-->
                    <button type="button"
                            onclick="createOrder('3', document.getElementById('paytype_3').value)"
                            class="btn btn-primary btn-rounded">
                        立即开通
                    </button>
                </li>
            </ul>
        </div>
        <!-- 支付二维码显示 -->
        <div class="row mt-3" id="qr" style="display:none; margin: 10px auto;">
            <div class="col-12 text-center">
                <div id="paydmftext" style="display:none; padding-bottom: 5px;">请用扫描二维码支付</div>
                <div id="qrcode"></div>
            </div>
        </div>
    </div>


    <!-- 卡密支付 -->
    <div class="row mt-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">卡密支付</h5>
                    <input id="kami" class="form-control mb-2" placeholder="在此输入您购买的卡密" value="">
                    <button class="btn btn-primary btn-block" id="kamivip">卡密激活</button>
                </div>
            </div>
        </div>
    </div>


</div>

<!-- 支付表单 -->
<form name="alipayment" id="alipayment" action="/pay/index" method="POST">
    <input type="hidden" name="paytype" id="epaytype" value="">
    <input type="hidden" name="id" id="epayid" value="">
</form>


{% endblock %}

{% block scripts %}
<script src="https://cdn.jsdelivr.net/npm/qrcodejs/qrcode.min.js"></script>
<script>
    function message(type, text) {
        const div = document.createElement('div');
        div.textContent = text;
        div.style.position = 'fixed';
        div.style.top = '5%';
        div.style.left = '50%';
        div.style.transform = 'translate(-50%, -50%)';
        div.style.padding = '10px 30px';
        div.style.background = '#fff';
        div.style.color = type === 'success' ? '#28a745' : '#dc3545';
        div.style.fontSize = '14px';
        div.style.border = `1px solid ${type === 'success' ? '#ccc' : '#dc3545'}`;
        div.style.borderRadius = '8px';
        div.style.boxShadow = '0 4px 15px rgba(0,0,0,0.2)';
        div.style.zIndex = 9999;
        div.style.opacity = 0;
        div.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        document.body.appendChild(div);
        requestAnimationFrame(() => {
            div.style.opacity = 1;
            div.style.transform = 'translate(-50%, -50%) scale(1)';
        });
        setTimeout(() => {
            div.style.opacity = 0;
            div.style.transform = 'translate(-50%, -50%) scale(0.9)';
            setTimeout(() => div.remove(), 300);
        }, 1500);
    }

    function ktvip(id) {
        if (!id) return message('error', '错误的开通方式');
        var paytype = $("#paytype_" + id).val();
        if (!paytype) return message('error', '请选择支付方式');

        $.ajax({
            url: "/pay/index",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({id: id, paytype: paytype}),
            success: function (res) {
                if (res.status == 100) {
                    message('success', '订单创建成功，请扫码支付');
                    console.log(res);
                    $("#qr").show();
                    $("#alipaydmftext").show();

                    new QRCode(document.getElementById("qrcode"), {
                        width: 210,
                        height: 210,
                        text: res.qr_code
                    });

                    // 启动轮询
                    pollPayStatus(res.orderid);
                } else {
                    message('error', res.msg);
                }
            }

        });
    }

    let pollInterval = null;
    // 创建订单并显示二维码
    async function createOrder(planId, paytype) {
        console.log(planId, paytype);
        if (!planId) {
            return message('error', '错误的开通方式');
        }
        if (!paytype) {
            return message('error', '请选择支付方式');
        }

        try {
            const payload = {id: planId, paytype: paytype};
            const res = await fetch('/pay/index', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                credentials: 'include',  // 🔑 确保带上 session/cookie
                body: JSON.stringify(payload)
            });

            if (!res.ok) {
                throw new Error("请求失败：" + res.status);
            }

            const data = await res.json();

            if (data.status === 100) {
                message('success', '订单创建成功，请扫码支付');
                if (paytype === 'alipay') {
                    document.getElementById("paydmftext").textContent = '请用支付宝扫描二维码支付';
                  } else if (paytype === 'wxpay') {
                    document.getElementById("paydmftext").textContent = '请用微信扫描二维码支付';
                  }

                // 显示二维码
                document.getElementById("qr").style.display = "block";
                document.getElementById("paydmftext").style.display = "block";
                document.getElementById("qrcode").innerHTML = "";
                new QRCode(document.getElementById("qrcode"), {
                    width: 180,
                    height: 180,
                    text: data.qr_code
                });

                // 启动轮询
                pollPayStatus(data.orderid);

            } else {
                alert(data.msg);
            }
        } catch (err) {
            console.error(err);
            // alert("订单创建失败：" + err.message);
            message('error', "订单创建失败");
        }
    }

    // 轮询支付宝支付状态
    async function pollPayStatus(outTradeNo) {
        if (pollInterval) clearInterval(pollInterval);

        pollInterval = setInterval(async () => {
            try {
                const res = await fetch('/pay/payquery', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({outTradeNo: outTradeNo})
                });
                const data = await res.json();

                if (data.status === 102) {  // 支付成功
                    clearInterval(pollInterval);
                    // alert("支付成功！用户权限已更新");
                    message('success', '支付成功！用户权限已更新');
                    // 延迟跳转，等待提示显示完成
                    setTimeout(() => {
                        window.location.href = "/user/dashboard";
                    }, 1600); // 1500ms + 动画缓冲
                } else if (data.status === 101) { // 未支付
                    console.log("等待支付...");
                } else {
                    clearInterval(pollInterval);
                    // alert("支付异常：" + data.status  +data.msg);
                    message('error', "支付异常");
                    // 刷新页面
                    location.reload();
                }
            } catch (err) {
                clearInterval(pollInterval);
                console.error(err);
                // alert("轮询支付状态失败：" + err.message);
                message('error', "轮询支付状态失败");
            }
        }, 3000); // 每3秒查询一次
    }

    //卡密
    document.getElementById('kamivip').addEventListener('click', async () => {
    const code = document.getElementById('kami').value.trim();
    if (!code) {
        return message('error', '请输入卡密');
    }

    try {
        const res = await fetch('/pay/kami', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ code })
        });

        const data = await res.json();
        if (data.status === 102) {
            message('success', '卡密激活成功，会员已开通');
            setTimeout(() => window.location.href = '/user/dashboard', 1000);
        } else {
            message('error', data.msg);
        }
    } catch (err) {
        console.error(err);
        message('error', '卡密激活失败');
    }
});


</script>

{% endblock %}
